<template>
	<el-dialog :title="form.id ? $t('common.editBtn') : $t('common.addBtn')" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="130px" v-loading="loading">
			<el-divider content-position="left">租户设置</el-divider>
			<el-row :gutter="20">
				<el-col :span="12" class="mb20">
					<el-form-item :label="t('tenant.name')" prop="name">
						<el-input v-model="form.name" :placeholder="t('tenant.inputnameTip')" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20" v-if="form.id === ''">
					<el-form-item label="管理员账号" prop="username">
						<el-input v-model="form.username" placeholder="请输入管理员账号" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item :label="t('tenant.code')" prop="code">
						<el-input v-model="form.code" :placeholder="t('tenant.inputcodeTip')" :disabled="form.id !== ''" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item :span="12" :label="t('tenant.tenantDomain')" prop="tenantDomain">
						<el-input v-model="form.tenantDomain" :placeholder="t('tenant.inputtenantDomainTip')" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item :span="12" :label="t('tenant.menuId')" prop="menuId">
						<el-select v-model="form.menuId" :placeholder="t('tenant.inputmenuIdTip')" clearable class="w100">
							<el-option v-for="item in menuData" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item :label="t('tenant.startTime')" prop="startTime">
						<el-date-picker v-model="form.startTime" type="date" :placeholder="t('tenant.inputstartTimeTip')" :value-format="dateTimeStr" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item :label="t('tenant.endTime')" prop="endTime">
						<el-date-picker v-model="form.endTime" type="date" :placeholder="t('tenant.inputendTimeTip')" :value-format="dateTimeStr" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="t('tenant.status')" prop="status">
						<el-radio-group v-model="form.status">
							<el-radio :label="item.value" v-for="(item, index) in status_type" border :key="index">{{ item.label }} </el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-divider content-position="left">套餐设置</el-divider>
				<el-col :span="12" class="mb20">
					<el-form-item label="设备数量(台)" prop="deviceTotal">
						<el-input-number
							controls-position="right"
							class="!w-full"
							:min="1"
							:step="1"
							:step-strictly="true"
							:precision="0"
							:max="99999"
							v-model="form.deviceTotal"
							placeholder="请输入设备数量"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="使用人数" prop="usersTotal">
						<el-input-number
							controls-position="right"
							class="!w-full"
							:min="1"
							:step="1"
							:step-strictly="true"
							:precision="0"
							:max="999"
							v-model="form.usersTotal"
							placeholder="请输入使用人数"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="历史数据期限(天)" prop="dataPeriod">
						<el-input-number
							controls-position="right"
							class="!w-full"
							:min="0"
							:step="1"
							:step-strictly="true"
							:precision="0"
							:max="999"
							v-model="form.dataPeriod"
							placeholder="请输入历史数据期限"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="短信数量(条)" prop="smgTotal">
						<el-input-number
							controls-position="right"
							class="!w-full"
							:min="0"
							:step="1"
							:step-strictly="true"
							:precision="0"
							:max="9999"
							v-model="form.smgTotal"
							placeholder="请输入短信数量"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="语音时长(分钟)" prop="voiceTotal">
						<el-input-number
							controls-position="right"
							class="!w-full"
							:min="0"
							:step="1"
							:step-strictly="true"
							:precision="0"
							:max="9999"
							v-model="form.voiceTotal"
							placeholder="请输入语音时长"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="公众推送" prop="officialAccountPush">
						<el-switch
							v-model="form.officialAccountPush"
							:active-value="20"
							:inactive-value="10"
							active-text="开启"
							inactive-text="关闭"
							inline-prompt
						/>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="移动终端" prop="mobileTerminal">
						<el-checkbox-group v-model="form.mobileTerminal">
							<el-checkbox label="10">安卓APP</el-checkbox>
							<el-checkbox label="20">微信小程序</el-checkbox>
							<el-checkbox label="30">微信公众号</el-checkbox>
							<el-checkbox label="40">H5</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="systemTenantDialog">
import { validateTenantCode, validateTenantName, validateTenantUsername } from '/@/api/admin/tenant';
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
import { getObj, addObj, putObj } from '/@/api/admin/tenant';
import { menuList } from '/@/api/admin/tenant-menu';
import { useI18n } from 'vue-i18n';
import { rule } from '/@/utils/validate';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);

// 字典
const { status_type } = useDict('status_type');

// 提交表单数据
const form = reactive({
	id: '',
	name: '',
	code: '',
	tenantDomain: '',
	startTime: '',
	endTime: '',
	status: '0',
	delFlag: '',
	createBy: '',
	updateBy: '',
	createTime: '',
	updateTime: '',
	menuId: '',
	username: '',
	deviceTotal: null,
	voiceTotal: null,
	smgTotal: null,
	usersTotal: null,
	officialAccountPush: 10,
	dataPeriod: null,
	mobileTerminal: [],
});

const menuData = ref([]);

// 定义校验规则
const dataRules = ref({
	name: [
		{ required: true, message: '名称不能为空', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				validateTenantName(rule, value, callback, form.id !== '');
			},
			trigger: 'blur',
		},
	],
	code: [
		{ required: true, message: '编码不能为空', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				validateTenantCode(rule, value, callback, form.id !== '');
			},
			trigger: 'blur',
		},
	],
	username: [
		{ required: true, message: '管理员账号不能为空', trigger: 'blur' },
		{ min: 5, max: 20, message: '管理员账号长度必须介于 5 和 20 之间', trigger: 'blur' },
		{ validator: rule.validatorAccount, trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				validateTenantUsername(rule, value, callback, form.id !== '');
			},
			trigger: 'blur',
		},
	],
	startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
	endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
	status: [{ required: true, message: 'status不能为空', trigger: 'blur' }],
	menuId: [{ required: true, message: '租户套餐不能为空', trigger: 'blur' }],
	deviceTotal: [{ required: true, message: '设备数量不能为空', trigger: 'blur' }],
	usersTotal: [{ required: true, message: '使用人数不能为空', trigger: 'blur' }],
	dataPeriod: [{ required: true, message: '历史数据期限不能为空', trigger: 'blur' }],
	smgTotal: [{ required: true, message: '短信数量不能为空', trigger: 'blur' }],
	voiceTotal: [{ required: true, message: '语音时长不能为空', trigger: 'blur' }],
});

// 打开弹窗
const openDialog = (id: string): void => {
	visible.value = true;
	form.id = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	if (id) {
		form.id = id;
		getTenantData(id);
	}
	getMenuList();
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		const mobileTerminal = form.mobileTerminal.length ? form.mobileTerminal?.filter((d) => !!d).join(',') : '';
		const params = Object.assign({}, form, { mobileTerminal: mobileTerminal });
		form.id ? await putObj(params) : await addObj(params);
		useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

/**
 * 初始化表格数据。
 * @param {string} id - 企业 ID。
 */
const getTenantData = async (id) => {
	const res = await getObj(id);
	Object.assign(form, res.data, { mobileTerminal: res.data?.mobileTerminal?.split(',')?.filter((d) => !!d) || [] });
};

/**
 * 获取菜单列表数据。
 */
const getMenuList = async () => {
	const res = await menuList();
	menuData.value = res.data;
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
